import { useEffect, useMemo, useState } from 'react'
import { NavBar, DatePicker } from 'antd-mobile'
import classNames from 'classnames'
import dayjs from 'dayjs'
import { useSelector } from 'react-redux'
import _ from 'lodash'

import DailyBill from './components/dailyBill/'

import './index.scss'

const Month = () => {
  /* 按月数据处理 */
  // 获取数据
  const billList = useSelector(state => state.billStore.billList)
  const monthGroup = useMemo(() => {
    return _.groupBy(billList, item => dayjs(item.date).format('YYYY - MM'))
  }, [billList])
  // 选择的月份数据
  const [selectedMonthList, setSelectedMonthList] = useState([])

  /* 时间选择器 */
  // 控制
  const [dateVisible, setDateVisible] = useState(false)
  // 时间数据
  const [currentDate, setCurrentDate] = useState(
    dayjs(Date.now()).format('YYYY - MM')
  )

  /* 根据月份数据计算支出 / 收入 / 结余 */
  const monthComputedResult = useMemo(() => {
    // 支出
    const pay = selectedMonthList
      .filter(item => item.type === 'pay')
      .reduce((prevTotal, currentItem) => prevTotal + currentItem.money, 0)
    // 收入
    const income = selectedMonthList
      .filter(item => item.type === 'income')
      .reduce((prevTotal, currentItem) => prevTotal + currentItem.money, 0)

    return {
      pay,
      income,
      total: pay + income
    }
  }, [selectedMonthList])

  /* 时间选择确认并筛选数据 */
  const dateConfirmFn = date => {
    // 获取选择的时间并格式化
    const selectedDate = dayjs(date).format('YYYY - MM')

    // 设置账单时间
    setCurrentDate(selectedDate)

    // 筛选选择月的数据
    setSelectedMonthList(monthGroup[selectedDate] || [])

    // 关闭选择器
    setDateVisible(false)
  }

  /* 初始化页面计算当前月的统计数据 */
  useEffect(() => {
    const currentMonthDate = dayjs(Date.now()).format('YYYY - MM')
    if (monthGroup[currentMonthDate]) {
      setSelectedMonthList(monthGroup[currentMonthDate])
    }
  }, [monthGroup])

  /* 选择月按照日分组 */
  const dayGroup = useMemo(() => {
    const groupData = _.groupBy(selectedMonthList, item => dayjs(item.date).format('YYYY-MM-DD'))
    const keys = Object.keys(groupData)
    return {
      groupData,
      keys
    }
  }, [selectedMonthList])

  /* 渲染 */
  return (
    <div className='monthlyBill'>
      <NavBar className='nav' backArrow={false}>
        月度收支
      </NavBar>

      <div className='content'>
        <div className='header'>
          {/* 时间切换区域 */}
          <div className='date'>
            <span className='text' onClick={() => setDateVisible(true)}>
              {`${currentDate}`}月账单
            </span>
            <span
              className={classNames('arrow', dateVisible && 'expand')}
            ></span>
          </div>
          {/* 统计区域 */}
          <div className='twoLineOverview'>
            <div className='item'>
              <span className='money'>{ Math.abs(monthComputedResult.pay).toFixed(2) }</span>
              <span className='type'>支出</span>
            </div>
            <div className='item'>
              <span className='money'>{ monthComputedResult.income.toFixed(2) }</span>
              <span className='type'>收入</span>
            </div>
            <div className='item'>
              <span className='money'>{ monthComputedResult.total.toFixed(2) }</span>
              <span className='type'>结余</span>
            </div>
          </div>
          {/* 时间选择器 */}
          <DatePicker
            className='kaDate'
            title='记账日期'
            precision='month'
            visible={dateVisible}
            closeOnMaskClick={true}
            onCancel={() => setDateVisible(false)}
            onConfirm={date => dateConfirmFn(date)}
            max={new Date()}
          />
        </div>
        {/* 单日列表统计 */}
        { dayGroup.keys.map(date => (
          <DailyBill key={date} date={date} billList={ dayGroup.groupData[date] } />
        )) }
      </div>
    </div>
  )
}

export default Month
